package com.yang.frost.blueberry.quartz.service;

import com.yang.frost.blueberry.quartz.entity.JobAndTrigger;
import com.yang.frost.blueberry.quartz.mapper.JobMapper;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 10296
 * @date 2021/1/24
 * @Description:
 */
@Configuration
@EnableScheduling
@Component
public class ScheduleRefreshService {

    private Logger logger = LoggerFactory.getLogger(ScheduleRefreshService.class);

    @Resource(name = "jobDetail")
    private JobDetail jobDetail;

    @Resource(name = "jobTrigger")
    private CronTrigger cronTrigger;

    @Resource(name = "scheduler")
    private Scheduler scheduler;

    @Autowired
    private JobMapper jobMapper;


    /**
     * 每隔5s查库，并根据查询结果决定是否重新设置定时任务
     *
     * @throws SchedulerException e
     */
    @Scheduled(fixedRate = 5000)
    public void scheduleCronTrigger() throws SchedulerException {
//        logger.info(">>>>>>>>>>>>>>每隔5秒查询一次数据库....");
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(cronTrigger.getKey());
        // 当前Trigger使用的
        String currentCron = trigger.getCronExpression();
        Map<String, Object> params = new HashMap<>();
        List<JobAndTrigger> list = jobMapper.list(params);
//        String searchCron = repository.findOne(1L).getCron();// 从数据库查询出来的
        //TODO 从数据库查询出来的
        String searchCron = "";
        if (currentCron.equals(currentCron)) {
            // 如果当前使用的cron表达式和从数据库中查询出来的cron表达式一致，则不刷新任务
        } else {
            // 表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(searchCron);
            // 按新的cronExpression表达式重新构建trigger
            trigger = (CronTrigger) scheduler.getTrigger(cronTrigger.getKey());
            trigger = trigger.getTriggerBuilder().withIdentity(cronTrigger.getKey())
                    .withSchedule(scheduleBuilder).build();
            // 按新的trigger重新设置job执行
            scheduler.rescheduleJob(cronTrigger.getKey(), trigger);
            currentCron = searchCron;
        }
    }

}
